package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import dao.SchoolDaoImpl;
import entity.School;
import exception.BaseException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
@WebServlet("/t1")
public class SchoolController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        String rep_jsonStr = JSONUtil.getJSON(request);
        JSONObject rep_jsonObj = JSON.parseObject(rep_jsonStr);
        if (rep_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息");
            response.getWriter().println(message_jsonObj);
            return;
        }

        try {
            Pagination pagination = ControllerHelper.getPagination(rep_jsonObj);
            Collection<School> schools = SchoolDaoImpl.getInstance().findAll();
            String schools_json = JSON.toJSONString(schools, JSONWriter.Feature.ReferenceDetection);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("data", schools_json);
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
        }
    }
}
